package com.kotlin.notes.json

import com.alibaba.fastjson.JSON
import com.alibaba.fastjson.TypeReference
import com.java.notes.json.ProductDTO
import com.java.notes.json.ResultDTO


class JsonParserDemoUsingJavaDTO {

    class TypeRef : TypeReference<ResultDTO<List<ProductDTO>>>()

    fun getProductList1(): List<ProductDTO>? {
        return getResultDTO().data
    }

    fun getProductList2(): List<ProductDTO>? {
        return getResultDTOUsingTypeRef().data
    }


    fun getResultDTOUsingTypeRef(): ResultDTO<List<ProductDTO>> {
        val json = """
        {"data":[{"children":[{"children":[],"id":"2","name":"二级产品线 A1"},{"children":[],"id":"3","name":"二级产品线 A2"}],"id":"1","name":"一级产品线 A"},{"children":[],"id":"4","name":"一级产品线 B"},{"children":[],"id":"5","name":"一级产品线 C"}],"success":true}
    """.trimIndent()

        val typeRef = TypeRef()
        val result = JSON.parseObject(json, typeRef)
        return result
    }

    fun getResultDTO(): ResultDTO<List<ProductDTO>> {
        val json = """
        {"data":[{"children":[{"children":[],"id":"2","name":"二级产品线 A1"},{"children":[],"id":"3","name":"二级产品线 A2"}],"id":"1","name":"一级产品线 A"},{"children":[],"id":"4","name":"一级产品线 B"},{"children":[],"id":"5","name":"一级产品线 C"}],"success":true}
    """.trimIndent()
        val result = JSON.parseObject(json, ResultDTO::class.java)
        val d = result.data as List<ProductDTO>

        return result as ResultDTO<List<ProductDTO>>
    }
}


fun main() {

    val demo = JsonParserDemoUsingJavaDTO()
    demo.getProductList1()
    demo.getProductList2()

    run {
        val result = demo.getResultDTO()
        val data = result.data
        println(data!!::class.java.canonicalName)
        println(data[0]!!::class.java.canonicalName)
    }

    run {
        val result = demo.getResultDTOUsingTypeRef()
        val data = result.data
        println(data!!::class.java.canonicalName)
        println(data[0]!!::class.java.canonicalName)
    }


}

